// json convert to table html


function ConvertToTable(ijson, tableid) {
    // console.log(tableid)
    // add table head 
    if (ijson.length >= 1) {
        var tab = document.getElementById(tableid);
        var tr1 = document.createElement("tr")
        tab.appendChild(tr1);
        for (let key in ijson[0]) {
            let th = document.createElement("th")
            th.innerHTML = key
            tr1.appendChild(th)
        }
        for (var i = 0; i < ijson.length; i++) {
            let tr = document.createElement("tr")
            tab.appendChild(tr);
            for (let key in ijson[i]) {
                let td = document.createElement("td")
                    // console.log(ijson[1][key])
                td.innerHTML = ijson[i][key]
                tr.appendChild(td)
            }
        }
    } else {
        document.createElement(p).innerHTML = "No data"
    }
};

function exportToCSV() {
    console.log("export to csv")
}


function removeRow() {

};

//转换成html表格，并带有编辑和删除控件
function ConvertToTableWithOption(ijson, tableid) {
    // console.log(tableid)
    // add table head 

    if (ijson.length >= 1) {
        var tab = document.getElementById(tableid);
        var tr1 = document.createElement("tr")
        tab.appendChild(tr1);
        for (let key in ijson[0]) {
            let th = document.createElement("th")
            th.innerHTML = key
            tr1.appendChild(th)
        }
        var colOPT = document.createElement("th");
        colOPT.innerHTML = "Option";
        tr1.appendChild(colOPT);

        for (var i = 0; i < ijson.length; i++) {
            let tr = document.createElement("tr")
            tab.appendChild(tr);
            for (let key in ijson[i]) {
                let td = document.createElement("td")
                    // console.log(ijson[1][key])
                td.innerHTML = ijson[i][key]
                tr.appendChild(td)
            }
            var del = document.createElement("td");
            del.innerHTML = "<a href='#' onclick='removeAlarmRecord(this)' >Remove</a> | <a href='#' onclick='editAlarmRecord(this)' >Edit</a>";
            tr.appendChild(del);
        }


    } else {
        document.createElement(p).innerHTML = "No data"
    }
};

function exportToCSV(jsonData) {

    //列标题，逗号隔开，每一个逗号就是隔开一个单元格
    let str = `姓名,电话,邮箱\n`;
    //增加\t为了不让表格显示科学计数法或者其他格式
    for (let i = 0; i < jsonData.length; i++) {
        for (let item in jsonData[i]) {
            str += `${jsonData[i][item] + '\t'},`;
        }
        str += '\n';
    }
    //encodeURIComponent解决中文乱码
    let uri = 'data:text/csv;charset=utf-8,\ufeff' + encodeURIComponent(str);
    //通过创建a标签实现
    let link = document.createElement("a");
    link.href = uri;
    //对下载的文件命名
    link.download = "json数据表.csv";
    link.text = "download"
    document.body.appendChild(link);
    // link.click();
    // document.body.removeChild(link);
}